import { getEx } from './crud'
export function queryThing(condition) {
    return new Promise((re, rej) => {
        getEx("thingQuery", "thing?condition=" + condition).then(res => {
            if (res && res.data && res.data.result) {
                re(res.data.result)
            } else {
                re([])
            }
        }).catch(err => {
            rej(err)
        })
    })
}

export function getAllThings() {
    return new Promise((re, rej) => {
        getEx("thingQuery/thingAll").then((res) => {
            if (res?.data?.result) {
                re(res.data.result)
            } else {
                re([])
            }
        }).catch(err => {
            rej(err)
        })
    })
}

export function getThings() {
    return new Promise((re, rej) => {
        getEx("thingQuery/thingAll").then((res) => {
            if (res && res.data && res.data.result) {
                let result = res.data.result
                let cache = {}
                let stations = []
                result.forEach(t => {
                    cache[t.uid] = t
                    if (t.is_station) {
                        t.children = []
                        t.state = "-"
                        if (t.parent_id == "") {
                            stations.push(t)
                        }
                    }
                });
                result.forEach(t => {
                    if (t.station_id) {
                        let p = cache[t.station_id]
                        if (p) {
                            if (!p.children) {
                                p.children = []
                            }

                            p.children.push(t)
                        }
                    }
                    if (t.parent_id) {
                        let p = cache[t.parent_id]
                        if (p) {
                            if (!p.children) {
                                p.children = []
                            }
                            p.children.push(t)
                        }
                    }
                })
                re(stations, cache)
            }
        }).catch(err => {
            rej(err)
        })
    })

}

export function getThingsOnline() {
    return new Promise((re, rej) => {
        getEx("thingQuery/thing/online").then(res => {
            if (res?.data?.result) {
                re(res.data.result)
            }
        }).catch(err => {
            rej(err)
        })
    })

}



export default {
    getThings,
    queryThing,
    getThingsOnline,
    getAllThings,
}